package cn.qiao.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
 
public class UdpServer {
 
    private int port;
 
    public UdpServer(int port) {
        this.port = port;
    }
 
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .option(ChannelOption.SO_BROADCAST, true)
             .handler(new UdpServerHandler());
 
            b.bind(port).sync().channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
    private class UdpServerHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            DatagramPacket packet = (DatagramPacket) msg;
            // 回应消息
            String response = "Received x bytes";
            byte[] responseBytes = response.getBytes();
            DatagramPacket responsePacket = new DatagramPacket(
                ctx.alloc().buffer().writeBytes(responseBytes), packet.sender());
            ctx.writeAndFlush(responsePacket);
        }
 
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
 
    public static void main(String[] args) throws Exception {
        int port = 8080; // 服务端口
        new UdpServer(port).run();
    }
}